package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import jcifs.smb.SmbFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


/**
 * 农行电子回单
 *
 * @author F
 */
public class ABC02Receipt extends ABC02Base implements IReceipt {
    // 交易传入的数据
    private String receiptSaveToMainDir = "";

    @Override
    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        // 余额查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (getBankConfig().getValueAsBool("manyReceiptDown")) {
                ABC02SyncTask abc02SyncTask = new ABC02SyncTask(p_reqReceipt.actNum, p_reqReceipt.actCur, p_reqReceipt.dateFrom, p_reqReceipt.dateTo);
                abc02SyncTask.bankFront = this.bankFront;
                abc02SyncTask.reqHeader = this.reqHeader;
                abc02SyncTask.download_ftp();
                retAts.respCode = "0";
                retAts.respInfo = "后台处理中";
            } else {
                String receiptRequestType = getBankConfig().getValueAsString("receiptRequestType");
                if ("sftp".equalsIgnoreCase(receiptRequestType)) {
                    retAts = downlaodForSftp(p_reqReceipt);
                } else {
                    retAts = download(p_reqReceipt);
                }
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsReceipt download(ReqQryReceipt p_reqReceipt) {
        // 回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

            Integer tmpFileCount = 0;//上传回单数量
            StringBuilder json = new StringBuilder();
            if (getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
            } else {
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }

            //按日循环
            while (tmpIntFrom <= tmpIntTo && StringHelper.isNullOrEmpty(retAts.respCode)) {
                //农行回单根据集团号一次查询当日所有子账号的回单，
                // 如果按照ats的逻辑每次查询的话会造成前置机文件异常(error:正由另一进程使用,因此该进程无法访问该文件)，所以在下载之前需要判断文件是否下载到了dsp，
                // 如果已经下载到dsp目录则无需重复下载，若没有下载过，发送请求，下载回单

                // 下载目录
                String localDir = FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + reqHeader.bankCode + File.separator + String.valueOf(tmpIntFrom).substring(0, 6) +
                        File.separator + String.valueOf(tmpIntFrom).substring(6, 8) + File.separator;
                String zipFileName = getBankConfig().getValueAsString("receiptZipFileNamePrefix") + "_" + tmpIntFrom + "_" + getBankConfig().getValueAsString("receiptZipFileNameSuffix");
                File zipFile = new File(localDir + zipFileName);
                String destPath = localDir;
                //判断银行前置机共享目录是否存在回单压缩文件，如果存在，再判断dsp本地目录是否存在

                if (StringHelper.hasAnyChar(bankFront.bankReceiptMainDir)) {
                    String trgFilePath = StringHelper.trimEndFileSp(bankFront.bankReceiptMainDir) + "/" + zipFileName;
                    SmbFile remoteFile = new SmbFile(trgFilePath);
                    //农行前置机共享目录存在文件
                    if (remoteFile.exists()) {
                        WriteBankLogLn("农行前置机共享目录存在回单压缩文件>>>>>>" + zipFileName);
                        if (zipFile.exists() && zipFile.isFile()) {
                            //DSP本地目录存在回单文件
                            WriteBankLogLn("DSP本地目录存在回单压缩文件>>>>>>" + zipFileName);
                            destPath += zipFileName.substring(0, zipFileName.lastIndexOf("."));
                            if (!new File(destPath).exists()) {
                                ZipHelper.unzipFile(localDir + File.separator + zipFileName, destPath);
                            }
                            tmpFileCount = writeReturnJson(destPath, json, retAts, p_reqReceipt);
                        } else {
                            //DSP本地目录没有回单文件
                            WriteBankLogLn("DSP本地目录没有回单压缩文件>>>>>>" + zipFileName);
                            WriteBankLogLn("从前置机共享目录:" + bankFront.bankReceiptMainDir + "下载回单文件到:" + localDir);
                            StringBuilder smbSb = new StringBuilder();
                            if (1 != SmbFileUtil.smbDownload(localDir, bankFront.bankReceiptMainDir, zipFileName, smbSb)) {
                                throw new Exception("请配置银行前置机回单目录:" + smbSb);
                            }
                            ZipHelper.unzipFile(localDir + File.separator + zipFileName, destPath);
                            destPath += zipFileName.substring(0, zipFileName.lastIndexOf("."));
                            tmpFileCount = writeReturnJson(destPath, json, retAts, p_reqReceipt);
                        }
                    } else {
                        WriteBankLogLn("农行前置机共享目录不存在回单压缩文件>>>>>>" + zipFileName);
                        if (zipFile.exists() && zipFile.isFile()) {
                            //DSP本地存在回单文件
                            WriteBankLogLn("DSP本地存在回单回单压缩文件>>>>>>" + zipFileName);
                            destPath += zipFileName.substring(0, zipFileName.lastIndexOf("."));
                            tmpFileCount = writeReturnJson(destPath, json, retAts, p_reqReceipt);
                        } else {
                            //DSP本地没有回单文件
                            //准备报文，发送请求
                            // 赋值通用参数
                            String receiptQuerySleepTime = getBankConfig().getValueAsString("receiptQuerySleepTime");
                            if (StringHelper.isNullOrEmpty(receiptQuerySleepTime)) {
                                receiptQuerySleepTime = "0";
                            }
                            Integer waitInteger = Integer.valueOf(receiptQuerySleepTime);
                            if (waitInteger > 0) {
                                WriteBankLogLn("发送下载报文前先等待" + waitInteger + "秒");
                                Thread.sleep(waitInteger * 1000);
                            }
                            WriteBankLogLn("发送请求报文获取回单文件>>>>>>");
                            ABC02Header bankHeader = new ABC02Header();
                            bankHeader.CCTransCode = "CMRA25";
                            bankHeader.ReqSeqNo = reqHeader.transSeqID;
                            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
                            writeCommonHeader(xmlWriter, bankHeader);
                            xmlWriter.writeStartDocument();
                            xmlWriter.writeStartElement("Corp");
                            xmlWriter.writeElementString("StartDate", String.valueOf(tmpIntFrom));
                            xmlWriter.writeElementString("AlterFlag", "1");
                            xmlWriter.writeEndElement();
                            xmlWriter.writeEndDocument();
                            // 调用接口、zip包自动上传到前置机文件夹里面
                            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//                            String[] tmpStrRet = new String[]{"", "<ap>\n" +
//                                    "    <Cmp>\n" +
//                                    "        <CmeSeqNo>070577301430</CmeSeqNo>\n" +
//                                    "        <BatchFileName>10999953500000027_20200114_CommonSingle_1.zip</BatchFileName>\n" +
//                                    "        <RespPrvData></RespPrvData>\n" +
//                                    "    </Cmp>\n" +
//                                    "    <FileFlag>1</FileFlag>\n" +
//                                    "    <CCTransCode>CMRA25</CCTransCode>\n" +
//                                    "    <RespSource>0</RespSource>\n" +
//                                    "    <RespCode>0000</RespCode>\n" +
//                                    "    <RespInfo>交易成功</RespInfo>\n" +
//                                    "    <RxtInfo></RxtInfo>\n" +
//                                    "    <RespDate>20200115</RespDate>\n" +
//                                    "    <RespTime>161205</RespTime>\n" +
//                                    "    <Cme>\n" +
//                                    "        <RecordNum>0</RecordNum>\n" +
//                                    "        <FieldNum>0</FieldNum>\n" +
//                                    "    </Cme>\n" +
//                                    "    <RespSeqNo></RespSeqNo>\n" +
//                                    "</ap>"};
                            if (tmpStrRet[0].length() == 0) {
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    String fileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                                    // 判断是否有文件包
                                    if (fileFlag != null && !fileFlag.equals("0")) {
                                        String fileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                                        File downLoadFile = new File(localDir + File.separator + fileName);
                                        //判断压缩文件是否存在，如果存在就不下载
                                        //ATSES-21963 农行电子回单重复 --范天星/2020/01/16
                                        //ATSES-23978 - 农行回单下载显示已经下载过无需重复下载但无法获取回单 --范天星/2020/03/20
                                        if (!downLoadFile.exists()) {
                                            if (StringHelper.hasAnyChar(bankFront.bankReceiptMainDir)) {
                                                WriteBankLogLn("从前置机共享目录:" + bankFront.bankReceiptMainDir + "下载回单文件到:" + localDir);
                                                StringBuilder smbSb = new StringBuilder();
                                                if (1 != SmbFileUtil.smbDownload(localDir, bankFront.bankReceiptMainDir, fileName, smbSb)) {
                                                    throw new Exception(smbSb.toString());
                                                }
                                            } else {
                                                throw new Exception("请配置银行前置机回单目录");
                                            }
                                            WriteBankLogLn("开始解压文件" + fileName);
                                            ZipHelper.unzipFile(localDir + File.separator + fileName, destPath);
                                        } else {
                                            WriteBankLogLn(fileName + "压缩文件已经下载过无需重复下载！");
                                        }
                                        destPath += fileName.substring(0, fileName.lastIndexOf("."));
                                        tmpFileCount = writeReturnJson(destPath, json, retAts, p_reqReceipt);

                                    } else {
                                        retAts.respCode = "0";
                                        retAts.respInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                                        WriteBankLogLn(tmpBkReader.getFirstText("/ap/RxtInfo"));
                                    }
                                } else {
                                    retAts.respCode = "0";
                                    retAts.respInfo = tmpSbMsg.toString();
                                    WriteBankLogLn(tmpSbMsg.toString());
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "未正常获取银行数据";
                                WriteBankLogLn("未正常获取银行数据");
                            }
                        }
                    }
                } else {
                    throw new Exception("请配置银行前置机回单目录");
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");

            json.append("]}");
            if (tmpFileCount.intValue() > 0) {
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }


        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
        return retAts;
    }

    private int writeReturnJson(String destPath, StringBuilder json, RetAtsReceipt retAts, ReqQryReceipt p_reqReceipt) {
        int tmpFileCount = 0;
        String[] parentFile = FileHelper.listFiles(destPath);
        if (parentFile == null) {
            WriteBankLogLn("解压后文件夹" + destPath + "下为空");
            return tmpFileCount;
        }
        for (String pfile : parentFile) {
            String[] files = FileHelper.listFiles(destPath + File.separator + pfile);
            if (files == null) {
                if (!pfile.endsWith(".txt")) {
                    WriteBankLogLn("解压后文件夹" + destPath + File.separator + pfile + "下为空");
                }
                continue;
            }
            //ATSES-21963 农行电子回单重复 --范天星/2020/01/16
            if (!pfile.equals(p_reqReceipt.actNum)) {
                continue;
            }
            for (String file : files) {
                //ATSES-26431 海克斯康农行查询电子回单返回有数据但是DSP显示无内容 && file.contains(p_reqReceipt.actNum)
                if ((file.endsWith(".PDF") || file.endsWith(".pdf")) && file.contains(p_reqReceipt.actNum)) {
                    // 1202027719900235368_20181225_18359000031.PDF
                    String localRecipt = destPath + File.separator + pfile + File.separator + file;
                    // 15158153900000098_20190219_15394101040030298_331480981_42001226408053004427_4600.48_37100331480981415809.pdf
                    String[] filenameSpliter = file.split("_");
                    if (filenameSpliter.length != 8) {
                        WriteBankLogLn("回单文件:" + file + "文件名错误");
                        continue;
                    }
                    String receiptUploadShared = this.getBankConfig().getValueAsString("receiptUploadShared");
                    if (StringHelper.isNullOrEmpty(receiptUploadShared) || "false".equalsIgnoreCase(receiptUploadShared)) {
                        try {
                            int result = -1;
                            String AtsFilePath = "";
                            String ftpFilePath = "";
                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                            String tmpByDate = Format.Date8Format.format(new Date());
                            tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                    + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                            if (new File(localRecipt).exists()) {
                                if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                    WriteBankLogLn(
                                            "正在上传文件至共享目录1:" + tmpByDate + FGBiz.dspCenter.dspSet.receiptShareDir);
                                    result = SmbFileUtil.smbUploading(localRecipt, tmpByDate,
                                            FGBiz.dspCenter.dspSet.receiptShareDir);
                                    AtsFilePath = tmpByDate + StringHelper.getFileName(localRecipt);//回单文件仓库存储路径
                                } else {
                                    //ftp服务器
                                    FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                    WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                    AtsFilePath = tmpByDate + new File(localRecipt).getName();//回单文件仓库存储路径
                                    //上传ftp服务器的地址
                                    ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" + AtsFilePath;
                                    WriteBankLogLn("开始将回单" + localRecipt + "上传至" + ftpFilePath);
                                    //上传至ftp
                                    result = FtpUtil.ftpUploading(ftpSet3, localRecipt, ftpFilePath);
                                }
                            }
                            if (result == 0 || result == 1) {
                                if (result == 0) {
                                    WriteBankLogLn("文件" + file + "上传成功");
                                    tmpFileCount++;
                                } else {
                                    WriteBankLogLn("文件" + file + "已存在共享目录无需重复上传");
                                }
                                // 推送数据给ATS处理
                                json.append("{");
                                json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                json.append("\"receiptCode\":\"" + filenameSpliter[3] + "\",");//日志号,暂定用日志号作为回单编号回传，与明细中日志号做匹配处理
                                json.append("\"receiptType\":\"" + "" + "\",");
                                json.append("\"receiptState\":\"" + "" + "\",");
                                if ("C".equals(filenameSpliter[7].substring(0, filenameSpliter[7].lastIndexOf(".")))) {
                                    //PDF中获取不到名称   后期通过明细匹配
                                    //String DbAccName = PdfGenerateUtil.getPdfTextPosition(localRecipt, "DbAccName");
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + filenameSpliter[4] + "\",");
                                    json.append("\"moneyway\":\"" + "2" + "\",");
                                } else {
                                    //PDF中获取不到名称   后期通过明细匹配
                                    //String CrAccName = PdfGenerateUtil.getPdfTextPosition(localRecipt, "CrAccName");
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + filenameSpliter[4] + "\",");
                                    json.append("\"moneyway\":\"" + "1" + "\",");
                                }
                                json.append("\"amount\":\"" + "" + filenameSpliter[5] + "\",");
                                json.append("\"tranSeqNo\":\"" + filenameSpliter[3] + "\",");
                                json.append("\"tranCode\":\"" + "" + "\",");
                                json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(filenameSpliter[1])) + "\",");
                                json.append("\"filePath\":\"" + AtsFilePath + "\",");
                                json.append("\"fileType\":\"1\"");
                                json.append("},");
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                                break;
                            }
                        } catch (Exception e) {
                            retAts.respCode = "-1";
                            retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                            break;
                        }
                    } else {
                        //保险


                    }
                }
            }
        }
        return tmpFileCount;
    }

    /**
     * sftp方式回单获取
     *
     * @param p_reqReceipt
     * @return
     */
    public RetAtsReceipt downlaodForSftp(ReqQryReceipt p_reqReceipt) throws IOException {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);

        SftpPortClient sftpPortClient = null;

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(Format.Date8Format.parse(p_reqReceipt.dateFrom));

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(Format.Date8Format.parse(p_reqReceipt.dateTo));

            int tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            while (tmpIntDateFrom <= tmpIntDateTo) {
                FtpSet ftpSet = bankFront.getFtpSet("receipt");
                ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
                WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始遍历服务器文件目录" + ftpSet.downDir);

                sftpPortClient = new SftpPortClient(ftpSet);
                ArrayList<String> ftpFileList = sftpPortClient.listNames(ftpSet.downDir);
                if (ftpFileList.size() == 0) {
                    continue;
                }
                FtpReceiver ftpReceiver = null;
                for (int i = 0; i < ftpFileList.size(); i++) {
                    String ftpFileName = ftpFileList.get(i);
                    WriteBankLogLn("服务器文件名[" + i + "]:" + ftpFileName);
                    if (ftpFileName.contains("_" + tmpIntDateFrom + "") && ftpFileName.contains(".zip")) {
                        ftpReceiver = sftpPortClient.downloadFile("", ftpFileName, receiptSaveToMainDir + File.separator + ftpFileName);
                        if (ftpReceiver.isCompleted) {
                            retAts.respCode = "0";

                            WriteBankLogLn("成功下载回单文件:" + ftpFileName + "至" + receiptSaveToMainDir);
                            String unzip = createTempFileDirectory();
                            WriteBankLogLn("回单压缩包保存本地路径:" + unzip);
                            ZipHelper.unzipFile(receiptSaveToMainDir + File.separator + ftpFileName, unzip);
                            String dirPath = unzip + File.separator + StringHelper.trimEnd(ftpFileName, ".zip") + File.separator + StringHelper.trimEnd(ftpFileName, ".zip");
                            WriteBankLogLn("解压后回单文件保存本地路径:" + dirPath);
                            String[] parentFile = FileHelper.listFiles(dirPath);
                            if (parentFile == null || (parentFile != null && parentFile.length == 0)) {
                                continue;
                            }
                            for (String pfile : parentFile) {
                                WriteBankLogLn("当前账号目录(文件名):" + pfile);
                                if (pfile.contains(p_reqReceipt.actNum)) {
                                    String[] files = FileHelper.listFiles(dirPath + File.separator + pfile);
                                    if (files == null || (files != null && files.length == 0)) {
                                        continue;
                                    }
                                    for (String pfiles : files) {
                                        WriteBankLogLn("本地账号:[" + p_reqReceipt.actNum + "]回单目录下当前pdf文件名:" + pfile);
                                        String filenameSpliter[] = pfiles.split("_");
                                        WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir + File.separator + "ABC" + File.separator);
                                        String receiptFile = dirPath + File.separator + pfile + File.separator + pfiles;
                                        //8位日期_本方账号_日志号_对方账号
                                        String[] fvs = StringHelper.splitFileNameAndExt(receiptFile);
                                        String fileName = fvs[0];
                                        String fileExt = fvs[1];
                                        String[] dirFileArray = fileName.split("_");
                                        String targetFileName = dirFileArray[1] + dirFileArray[2] + dirFileArray[3] + dirFileArray[4];
                                        String targetDir = StringHelper.getDirPathUsingSplitGiveUpLastOne(targetFileName, 3);
                                        String targetPath = FGBiz.dspCenter.dspSet.receiptShareDir + File.separator + "ABC" + File.separator + targetDir + File.separator + targetFileName + "." + fileExt;
                                        WriteBankLogLn("源文件路径:" + receiptFile);
                                        WriteBankLogLn("目标文件路径:" + targetPath);
                                        FileHelper.copyFile(receiptFile, targetPath);
                                        if (new File(targetPath).exists()) {
                                            WriteBankLogLn("推送共享目录成功.");
                                            File localReceiptFile = new File(receiptFile);
                                            if (localReceiptFile.exists()) {
                                                WriteBankLogLn("开始删除本地临时下载回单文件:" + receiptFile);
                                                boolean isDeleted = localReceiptFile.delete();
                                                if (isDeleted) {
                                                    WriteBankLogLn("本地临时下载回单文件:[" + receiptFile + "]删除成功");
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    WriteBankLogLn("当前账号:[" + pfile + "]和目标账号:[" + p_reqReceipt.actNum + "]不匹配,无需解析上传回单!");
                                }
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState;
                            WriteBankLogLn(ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                        }
                    }
                }
                tmpCalendarFrom.add(Calendar.DATE, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                p_reqReceipt.dateFrom = Format.Date8Format.format(tmpCalendarFrom.getTime());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (sftpPortClient != null) {
                sftpPortClient.disconnect();
            }
        }

        return retAts;
    }


    public static boolean fileRead(String filePath, String chars) throws Exception {
        BufferedReader bReader = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                FileReader reader = new FileReader(file);
                bReader = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String s = "";
                while ((s = bReader.readLine()) != null) {
                    sb.append(s);
                }
                bReader.close();
                String str = sb.toString();
                return str.contains(chars);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            bReader.close();
        }
        return false;
    }


    /**
     * 将字符串追加到文件已有内容后面
     *
     * @param fileFullPath 文件完整地址：D:/test.txt
     * @param content      需要写入的
     */
    public static void writeFile(String fileFullPath, String content) throws IOException {
        FileOutputStream fos = null;
        try {
            File tmpFile = new File(fileFullPath);
            File parentDir = new File(tmpFile.getParent());
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            if (!tmpFile.exists()) {
                tmpFile.createNewFile();
            }
            //true不覆盖已有内容
            fos = new FileOutputStream(fileFullPath, true);
            //写入
            fos.write(content.getBytes());
            // 写入一个换行
            fos.write("\r\n".getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }
}
